package utils

import (
	crypto_rand "crypto/rand"
	_ "embed"
	"encoding/binary"
	"fmt"
	"github.com/go-resty/resty/v2"
	"io/ioutil"
	math_rand "math/rand"
	"os"
	"time"
)

////go:embed ua
//var uaList string
//
//func GetRandomUa() string {
//	ua := strings.Split(uaList, "\r\n")
//	return ua[rand.Intn(len(ua))]
//}

func RandomEmail(length int) string {
	math_rand.Seed(time.Now().UnixNano())
	const letterBytes = "abcdefghijklmnopqrstuvwxyz123456789"
	b := make([]byte, length)
	for i := range b {
		b[i] = letterBytes[math_rand.Intn(len(letterBytes))]
	}
	return fmt.Sprintf("%s@ytmail.top", string(b))
}

func RandomInt(start int, end int) int {
	var b [8]byte
	_, err := crypto_rand.Read(b[:])
	if err != nil {
		panic("cannot seed math/rand package with cryptographically secure random number generator")
	}
	math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))

	random := math_rand.Intn(end - start)
	random = start + random
	return random
}

func Choice(values []string) string {
	//math_rand.Seed(time.Now().Unix()) // initialize global pseudo random generator
	var b [8]byte
	_, err := crypto_rand.Read(b[:])
	if err != nil {
		panic("cannot seed math/rand package with cryptographically secure random number generator")
	}
	math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
	return values[math_rand.Intn(len(values))]
}

func WriteFile(filename, text string) {
	f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}

	defer f.Close()

	if _, err = f.WriteString(fmt.Sprintf("%s", text)); err != nil {
		ioutil.WriteFile("writefile_error.txt", []byte(err.Error()), 0644)
	}
}

func ArrayCountValues(s []interface{}) map[interface{}]uint {
	r := make(map[interface{}]uint)
	for _, v := range s {
		if c, ok := r[v]; ok {
			r[v] = c + 1
		} else {
			r[v] = 1
		}
	}

	return r
}

func RemoveDuplicateStr(strSlice []string) []string {
	allKeys := make(map[string]bool)
	var list []string
	for _, item := range strSlice {
		if _, value := allKeys[item]; !value {
			allKeys[item] = true
			list = append(list, item)
		}
	}
	return list
}

func CheckIp(proxy string) (resp *resty.Response, err error) {
	client := resty.New()
	client.SetRetryCount(3)
	if proxy != "" {
		client.SetProxy(proxy)
	}

	resp, err = client.R().Get("https://www.lumtest.com/myip.json")
	return
}